package com.contactsconverter.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.difsonapps.contacttranslator.dto.NumberDTO;
import com.difsonapps.contacttranslator.dto.NumberTypeEnum;



public class CTSIMDao {

	private CTSIMDao(){}

	private static CTSIMDao INSTANCE_CTSIMDao = new CTSIMDao();
	private static Context context;
	private static CTSQLiteHelper cTSQLiteHelper;
	private static SQLiteDatabase sQLiteDatabase;
	public static CTSIMDao getINSTANCE(Context ct){
		context = ct;
		if(sQLiteDatabase == null){
			cTSQLiteHelper = new CTSQLiteHelper(context);
			sQLiteDatabase = cTSQLiteHelper.getDatabase();
		}
		return INSTANCE_CTSIMDao;
	}



	public NumberDTO save(NumberDTO numberDTO){
		try{

			ContentValues values = new ContentValues();
			values.put(CTContrat.CTSIM._ID, getMaxID()+1);
			values.put(CTContrat.CTSIM.COLUMN_NAME_NUMBER,numberDTO.getValue());

			long idord = sQLiteDatabase.insert(
					CTContrat.CTSIM.TABLE_NAME,
					"null",
					values);
			numberDTO.setId(idord);
			Log.e(CTSIMDao.class.getName(), "idord "+idord);
		}catch (Exception e) {
			Log.e(CTSIMDao.class.getName(), e.getMessage()+"");
		}	
		return numberDTO;
	}

	private long getMaxID(){
		try{
			final String QUERY = "SELECT max("+CTContrat.CTSIM._ID+") FROM "+CTContrat.CTSIM.TABLE_NAME;
			Cursor cursor = sQLiteDatabase.rawQuery(QUERY, new String[]{});
			cursor.moveToFirst();
			if(cursor.getCount()!=0)
				return cursor.getLong(0);
			cursor.close();
		}catch (Exception e) {
			Log.e(CTSIMDao.class.getName(), e.getMessage()+"");
		}
		return 0;
	}

	public List<NumberDTO> getAll(){
		List<NumberDTO> listOfNumber = new ArrayList<NumberDTO>();
		Cursor cursor = null ;
		try{
			final String QUERY = "SELECT * FROM "+CTContrat.CTSIM.TABLE_NAME;
			cursor = sQLiteDatabase.rawQuery(QUERY, new String[]{});
			if(cursor.getCount() > 0)
				while (cursor.moveToNext()) {
					listOfNumber.add(new NumberDTO(cursor.getString(1), NumberTypeEnum.MOBILE));				
				}
			
		}catch (Exception e) {
			Log.e(CTSIMDao.class.getName(), e.getMessage()+"");
		}
		if(cursor != null )cursor.close();
		return listOfNumber;
	}

	public void deleteAll(){
		try{

			final String QUERY = "DELETE  FROM "+CTContrat.CTSIM.TABLE_NAME+" WHERE 1;";
			sQLiteDatabase.rawQuery(QUERY, new String[]{});

		}catch (Exception e) {
			Log.e(CTSIMDao.class.getName(), e.getMessage()+"");
		}

	}

}
